<?php

require_once("../models/config.php");
require_once("../ui.php");
require_once("../stats/db.php");
include_once("bar.graph.php");

if (!isUserViewAuthorized()) {
	echo "Unauthorized access";
	die();
}

global $loggedInUser;
global $db;

function createToolUsefulnessSqlCommand($toolsCategory) {

	$sql = "SELECT `debugging_Tools`.`Name` AS ToolName, `usefulness`.`Description` AS Usefulness, COUNT(*) AS Count FROM `debugging_Tool_Usages` JOIN `debugging_Tools` ON `Debugging_Tool` = `debugging_Tools`.`Id` JOIN `debugging_Reports` ON `Debugging_Report` = `debugging_Reports`.`Id` JOIN `userCake_Users` ON `debugging_Reports`.`User` = `userCake_Users`.`User_ID` JOIN `debugging_Tool_Categories` ON `debugging_Tools`.`CategoryId` = `debugging_Tool_Categories`.`Id` JOIN `usefulness` ON `debugging_Tool_Usages`.`Useful_Usage`= `usefulness`.`Id`

		WHERE (`userCake_Users`.`Group_Id` = " . STANDART_USER_GROUP_ID . ") AND (`debugging_Tool_Categories`.`Id` = $toolsCategory)
		GROUP BY `debugging_Tools`.`Id`, `debugging_Tool_Usages`.`Useful_Usage`
		ORDER BY `debugging_Tools`.`Name`, `usefulness`.`Id`
		";

	return $sql;
}

$category = readGet('categoryId');
if (!is_numeric($category)) {
	echo "Category id " . htmlspecialchars($category) . " is not numeric";
	return;
}

$sql = "SELECT `Name` AS Name FROM `debugging_Tool_Categories` WHERE `Id` = $category";
$result = $db->sql_query($sql);
if (!$result) {
	$error = $db->sql_error();
	return;
}

$row = $db->sql_fetchrow();
$categoryName = $row['Name'];

$sql = createToolUsefulnessSqlCommand($category);
$result = $db->sql_query($sql);
if (!$result) {
	$error = $db->sql_error();
	return;
}

$rows = $db->sql_fetchall();

$toolNames = array();
$usefulnesses = array();
foreach($rows as $i => $row) {
	$toolNames[$row['ToolName']][$row['Usefulness']] = $row['Count'];
}

$usefulnesses = getUsageCategories();

$series = array();
foreach($usefulnesses as $i => $usefulness) {
	
	$usefulnessDesc = $usefulness->description;
	
	$series[$usefulnessDesc] = array();
	foreach($toolNames as $toolName => $toolData) {
		$count = (array_key_exists($usefulnessDesc, $toolData) ? $toolData[$usefulnessDesc] : 0); 
		
		$series[$usefulnessDesc][] = $count;
	}
}

$colors = array(array("R"=>255,"G"=>122,"B"=>122),
array("R"=>245,"G"=>245,"B"=>0),
array("R"=>122,"G"=>245,"B"=>0));

drawMyStackedBarGraph($series, "Usages", array_keys($toolNames), "Tool subcategory",
	"Usefulness for tools in category '$categoryName'", $colors);

?>